import { Component, Input, OnInit, ViewChild, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd";
import { FcsService } from "../../service/fcs.service";

@Component({
  selector: 'app-fcs-create-trigger',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './fcs-create-trigger.component.html',
  styleUrls: ['./fcs-create-trigger.component.less']
})
export class FcsCreateTriggerComponent implements OnInit {
  @Input() triggersData;

  triggerRule: string = 'static';
  isCrontab: boolean = false;
  staticNum: number = 1;
  staticUnit: string = 'm';
  staticConfig: string = '';
  timeList = [
    { label: '分钟', value: 'm' },
    { label: '小时', value: 'h' }
  ];

  isEnable: boolean = false; //是否启用
  openInvokeEvent: boolean = false; //是否自定义消息
  invokeEvent: string = '';
  invokeEventTpl = "{\r\n    \"key\": \"value\"\r\n}";
  editorOptions = {
    language: "json",
    fontFamily: 'Monaco, Menlo, "Ubuntu Mono", Consolas, source-code-pro, monospace;',
    fontSize: "16",
    theme: 'vs'
  };

  isLoadingBucket: boolean = false;
  ossBucketList = [];

  ossTriggerList = [
    { "label": "ObjectCreated:*", "value": "ObjectCreated:*" },
    { "label": "ObjectCreated:Put", "value": "ObjectCreated:Put" },
    { "label": "ObjectCreated:Copy", "value": "ObjectCreated:Copy" },
    { "label": "ObjectCreated:CompleteMultipartUpload", "value": "ObjectCreated:CompleteMultipartUpload" },
    { "label": "ObjectRemoved:*", "value": "ObjectRemoved:*" },
    { "label": "ObjectRemoved:Delete", "value": "ObjectRemoved:Delete" },
    { "label": "ObjectRemoved:DeleteMarkerCreated", "value": "ObjectRemoved:DeleteMarkerCreated" },
  ];
  ossTriggerPre: string;
  ossTriggerSuf: string;
  isLoadingApigGroup: boolean = false;
  apigGroupList = [];
  apigEnvironmentList = [
    { "label": "线上", "value": "1" },
    { "label": "测试", "value": "2" }
  ];
  apigAuthList = [
    { "label": "无认证", "value": "0" },
    { "label": "IAM认证", "value": "1" },
    { "label": "APP认证", "value": "2" },
  ]
  apigProtocalList = [
    { "label": "HTTP", "value": "0" },
    { "label": "HTTPS", "value": "1" }
  ];
  apigMethodList = [
    { "label": "GET", "value": "0" },
    { "label": "POST", "value": "1" },
    { "label": "PATCH", "value": "2" },
    { "label": "PUT", "value": "3" },
    { "label": "OPTIONS", "value": "4" },
    { "label": "DELETE", "value": "5" },
    { "label": "HEAD", "value": "6" },
  ];
  authenticationMode: string = '0';
  requestProtocol: string = '0';
  requestMethod: string = '0';
  //创建函数，创建触发器校验参数，控制样式的
  errorTriggerName: boolean = false;
  errorCrontab: boolean = false;
  errorOssBucket: boolean = false;
  errorOssTrigger: boolean = false;
  errorBacktimeout: boolean = false;
  errorApiggroupid: boolean = false;
  errorApigenvironment: boolean = false;
  errorAuthentica: boolean = false;
  errorApigproto: boolean = false;
  errorRequestmethod: boolean = false;
  //最终校验时，要检验的参数
  crontab: string;
  ossBucket: string;
  ossTrigger: string;
  apigGroupId: string;
  releaseValue: string = '2';
  backendTimeout: string;
  constructor(private fb: FormBuilder,
    private msgService: NzMessageService,
    private cdr: ChangeDetectorRef,
    private fcsService: FcsService) {

  }

  ngOnInit() {
    this.initData();
    this.getOssBuckets();
    this.getApigGroup();
  }

  initData() {
    for (let i = 0; i < this.triggersData.length; i++) {
      let data = this.triggersData[i];
      if (data.type === 'timer') {
        if (!data.triggerRule) {
          data.triggerRule = 'static';
          data.staticNum = 1;
          data.staticUnit = 'm';
        }
      }
    }
  }

  triggerRuleChange(data) {
    if (data.triggerRule === 'cron') {
      data.isCrontab = true;
    } else if (data.triggerRule === 'static') {
      data.isCrontab = false;
    }
  }

  staticChange(staticNum) {
    this.staticNum = staticNum.toString();
    this.staticConfig = "@every " + `${this.staticNum}${this.staticUnit}`;
  }

  staticUnitChange(staticUnit) {
    this.staticUnit = staticUnit;
    this.staticConfig = "@every " + `${this.staticNum}${this.staticUnit}`;
  }

  openInvokeEventChange(data, openInvokeEvent) {
    if (openInvokeEvent) {
      if (data.invokeEvent === "") {
        data.invokeEvent = this.invokeEventTpl;
      }
    }
    this.openInvokeEvent = openInvokeEvent;
  }

  crontabChange(data, crontab) {
    if (crontab === '') {
      data.errorCrontab = true;
    } else if (crontab && crontab.length > 0) {
      data.errorCrontab = false;
    }
    this.crontab = crontab;
  }

  getOssBuckets() {
    this.isLoadingBucket = true;
    this.fcsService.getOssBucketList(1, 10000).subscribe(res => {
      if (res && res['data']) {
        let resBuckets = res.data;
        if (this.ossBucketList.length <= 0) {
          resBuckets.forEach(item => {
            this.ossBucketList.push({ label: item.bucketName, value: item.bucketName });
          })
        }
      }
      this.isLoadingBucket = false;
    }, err => {
      this.isLoadingBucket = false;
      this.msgService.error('网络错误');
    })
  }

  ossBucketChange(data, ossBucket) {
    if (ossBucket === '') {
      data.errorOssBucket = true;
    } else if (ossBucket && ossBucket.length > 0) {
      data.errorOssBucket = false;
    }
    this.ossBucket = ossBucket;
  }

  triggerNameChange(data) {
    if (!data.name) {
      data.errorTriggerName = true;
    } else {
      data.errorTriggerName = false;
    }
  }

  ossTriggerChange(data, ossTrigger) {
    if (ossTrigger === '') {
      data.errorOssTrigger = true;
    } else if (ossTrigger && ossTrigger.length > 0) {
      data.errorOssTrigger = false;
    }
    this.ossTrigger = ossTrigger;
  }

  apigGroupIdChange(data, apigGroupId) {
    this.apigGroupId = apigGroupId;
    if (!apigGroupId) {
      data.errorApiggroupid = true;
    } else {
      data.errorApiggroupid = false;
    }
  }

  getApigGroup() {
    this.isLoadingApigGroup = true;
    this.fcsService.getApigGroupList().subscribe(res => {
      this.isLoadingApigGroup = false;
      this.apigGroupList = res['data'] || [];
    }, err => {
      this.apigGroupList = [];
      this.isLoadingApigGroup = false;
    })
  }

  releaseChange(data, release) {
    this.releaseValue = release;
    if (!release) {
      data.errorApigenvironment = true;
    } else {
      data.errorApigenvironment = false;
    }
  }

  authenticationModeChange(data, authenticationMode) {
    this.authenticationMode = authenticationMode;
    if (!authenticationMode) {
      data.errorAuthentica = true;
    } else {
      data.errorAuthentica = false;
    }
  }

  requestProtocolChange(data, requestProtocol) {
    this.requestProtocol = requestProtocol;
    if (!requestProtocol) {
      data.errorApigproto = true;
    } else {
      data.errorApigproto = false;
    }
  }

  requestMethodChange(data, requestMethod) {
    this.requestMethod = requestMethod;
    if (!requestMethod) {
      data.errorRequestmethod = true;
    } else {
      data.errorRequestmethod = false;
    }
  }

  backendTimeoutChange(data, backendTimeout) {
    this.backendTimeout = backendTimeout;
    let pattern = new RegExp('^[1-9][0-9]{0,8}$');
    if (!pattern.test(this.backendTimeout)) {
      data.errorBacktimeout = true;
    } else {
      data.errorBacktimeout = false;
    }
  }

  validate(): boolean {
    let res: boolean = true; //假设校验通过
    for (let i = 0; i < this.triggersData.length; i++) {
      let data = this.triggersData[i];
      if (data.type === 'timer') {
        if (data.triggerRule === 'cron') {
          if (!data.crontab) {
            data.errorCrontab = true;
            res = false;
          } else {
            data.errorCrontab = false;
          }
        }
      } else if (data.type === 'oss') {
        if (!data.ossBucket) {
          data.errorOssBucket = true;
          res = false;
        } else {
          data.errorOssBucket = false;
        }
        if (!data.ossTrigger) {
          data.errorOssTrigger = true;
          res = false;
        } else {
          data.errorOssTrigger = false;
        }
      } else if (data.type === 'apig') {
        if (!data.apigGroupId) {
          data.errorApiggroupid = true;
          res = false;
        } else {
          data.errorApiggroupid = false;
        }
        if (!data.releaseValue) {
          data.errorApigenvironment = true;
          res = false;
        } else {
          data.errorApigenvironment = false;
        }
        if (!data.authenticationMode) {
          data.errorAuthentica = true;
          res = false;
        } else {
          data.errorAuthentica = false;
        }
        if (!data.requestProtocol) {
          data.errorApigproto = true;
          res = false;
        } else {
          data.errorApigproto = false;
        }
        if (!data.requestMethod) {
          data.errorRequestmethod = true;
          res = false;
        } else {
          data.errorRequestmethod = false;
        }
        if (!(new RegExp('^[1-9][0-9]{0,8}$')).test(data.backendTimeout)) {
          data.errorBacktimeout = true;
          res = false;
        } else {
          data.errorBacktimeout = false;
        }
      }
    }
    this.cdr.markForCheck();
    this.cdr.detectChanges();
    return res;
  }

  /**
   * 校验通过后，传递的要创建的 trigger 的数据
   */
  submitData(): any {
    for (let i = 0; i < this.triggersData.length; i++) {
      let data = this.triggersData[i];
      let name = data['name'];
      let type = data['type'];
      let targetName = 'LATEST';
      if (type === 'timer') {
        if (data.triggerRule === 'cron') {
          data['config'] = data.crontab;
        } else if (data.triggerRule === 'static') {
          data['config'] = "@every " + data.staticNum + data.staticUnit;
        }
      } else if (type === 'oss') {
        let ossParam;
        ossParam = {
          "bucketName": data.ossBucket,
          "event": "s3:" + data.ossTrigger,//在选择的事件类型前面加上 "s3:"
          "keyFilterRules": {
            "prefix": data.ossTriggerPre,
            "suffix": data.ossTriggerSuf
          },
        };
        data['config'] = JSON.stringify(ossParam);
      } else if (type === 'apig') {
        let apigConfig = {
          groupId: data.apigGroupId,
          isRelease: data.releaseValue,
          authenticationMode: data.authenticationMode,
          requestProtocol: data.requestProtocol,
          requestMethod: data.requestMethod,
          backendTimeout: data.backendTimeout
        };
        data['config'] = JSON.stringify(apigConfig);
      }
    }
    return this.triggersData;
  }
}
